#!/bin/bash
set -e
set +e
echo -e "\n\033[32m\t*********start ninja pacakge build*********\033[0m\n"

if [[ "$(uname)" == "Linux" ]]; then
    current_os="linux"
elif [[ "$(uname)" == "Darwin" ]]; then
    current_os="darwin"
else
    current_os="unknown"
fi

ARCH=$(uname -m)
if [ "$ARCH" = "x86_64" ]; then
    ARCH="x86"
elif [ "$ARCH" = "aarch64" ]; then
    ARCH="arm"
fi

current_path=$(pwd)
current_date=$(date +%Y%m%d)
mkdir -p build/config
touch build/config/BUILDCONFIG.gn

pushd $current_path > /dev/null
  git clone https://gitcode.com/openharmony/third_party_ninja.git
  pushd $current_path/third_party_ninja > /dev/null
    echo "start compile ninja binary file"
    python3 ./configure.py --bootstrap
    strip ninja && chmod +x ninja
    echo "compile ninja binary file finish"
    ninja_version=$(./ninja --version)
    echo "current ninja version is ${ninja_version}"
    mkdir ninja_package
    pushd $current_path/third_party_ninja/ninja_package > /dev/null
      wget https://repo.huaweicloud.com/harmonyos/compiler/ninja/1.12.0/linux/ninja-linux-x86-1.12.0-20251011.tar.gz && tar -zxvf ninja-linux-x86-1.12.0-20251011.tar.gz
      rm ninja-linux-x86-1.12.0-20251011.tar.gz && rm ninja
      mv ../ninja ./
      sed -i "s/1\.12\.0/$ninja_version/g" README.OpenSource
      package_name="ninja-${current_os}-${ARCH}-${ninja_version}-${current_date}.tar.gz"
      tar -zcvf $package_name ./*
      mv $package_name ../../
      rm ninja
    popd > /dev/null
    rm -rf CMakeCache.txt && rm -rf CMakeFiles/ && rm -rf CTestTestfile.cmake && rm -rf DartConfiguration.tcl && rm -rf _deps && rm -rf cmake_install.cmake
  popd > /dev/null
popd > /dev/null

if [[ $current_os == "linux" ]]; then
  echo "start compile ohos version ninja  binary file"
  pushd $current_path > /dev/null
    python3 ./download_sdk.py
    pushd $current_path/prebuilts > /dev/null
      tar -zxvf version-*.tar.gz .
      pushd $current_path/prebuilts/linux/ > /dev/null
        unzip native-linux*.zip
      popd > /dev/null
    popd > /dev/null
    export PATH=$current_path/prebuilts/linux/native/build-tools/cmake/bin:$PATH
    pushd $current_path/third_party_ninja > /dev/null
      cmake -GNinja -DOHOS_STL=c++_shared -DOHOS_PLATFORM=OHOS -DCMAKE_TOOLCHAIN_FILE=$current_path/prebuilts/linux/native/build/cmake/ohos.toolchain.cmake -DBUILD_TESTING=OFF
      cmake --build .
      mv ninja ninja_package/
      rm -rf CMakeCache.txt && rm -rf CMakeFiles/ && rm -rf CTestTestfile.cmake && rm -rf DartConfiguration.tcl && rm -rf _deps && rm -rf cmake_install.cmake
    popd > /dev/null
    pushd $current_path/third_party_ninja/ninja_package > /dev/null
      package_name="ninja-ohos-${ninja_version}-${current_date}.tar.gz"
      tar -zvcf $package_name ./*
      mv $package_name ../../
      rm ninja 
    popd > /dev/null
  popd > /dev/null
  echo "build ohos ninja binary finish"
fi
